import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import type { DeleteChatMessagesRequest, DeleteChatMessagesResponse } from '@/types/chat';

// POST /api/client/chat/messages/delete-after - 删除指定消息之后的所有聊天记录
async function handlePost(request: NextRequest): Promise<DeleteChatMessagesResponse> {
  // 1. 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  // 2. 获取当前用户ID
  const userId = authResult.user?.id;
  if (!userId) {
    throw new Error('用户信息不存在');
  }

  // 3. 解析请求参数
  const body: DeleteChatMessagesRequest = await request.json();
  const { chatId, messageId } = body;

  // 4. 必填字段验证
  if (!chatId) {
    throw new Error('聊天会话ID为必填项');
  }

  if (!messageId) {
    throw new Error('消息ID为必填项');
  }

  // 5. 验证会话是否属于当前用户
  const session = await prisma.chatSession.findFirst({
    where: {
      chatId,
      userId
    }
  });

  if (!session) {
    throw new Error('会话不存在或无权限');
  }

  // 6. 找到指定的消息
  const targetMessage = await prisma.chatMessage.findFirst({
    where: {
      id: messageId,
      sessionId: session.id
    }
  });

  if (!targetMessage) {
    throw new Error('消息不存在');
  }

  // 7. 执行删除
  const deletedMessages = await prisma.chatMessage.deleteMany({
    where: {
      sessionId: session.id,
      createdAt: {
        gt: targetMessage.createdAt
      }
    }
  });

  // 8. 返回结果
  return {
    success: true,
    deletedCount: deletedMessages.count
  };
}

export const POST = withMiddleware(handlePost);